
<template>
  <div>
    显示：{{ show }} &nbsp;&nbsp; len: {{ count }} &nbsp;&nbsp; time: {{ time }}ms
    <br/>
    <button @click="onToggle">显示/隐藏</button>
    &nbsp;&nbsp;
    <button @click="onBg('red')">红色</button>
    &nbsp;&nbsp;
    <button @click="onBg('green')">绿色</button>
    &nbsp;&nbsp;
    <button @click="count += 10000">添加</button>
    <hr/>
    <div style="width: 100%; max-height: 90vh; overflow: auto;">
      <template v-if="show" v-for="item in count" :key="item">
        <span @mouseover="onMouseover" @mouseout="onMouseout" :id="'box_' + item" class="box" :style="{ backgroundColor: color }"></span>
      </template>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'

const show = ref(true)
const time = ref(0)
const color = ref('red');
const count = ref(200000);


const onToggle = () => {
  show.value = !show.value
  
  if (!show.value) return ;

  let t = performance.now()
  let timer:any;
  timer = setInterval(() => {
    if (document.getElementById('box_' + (count.value - 1))){
      time.value = Math.floor(performance.now() - t)
      timer && clearInterval(timer);
    }
  }, 50);
}

const onBg = (c: string) => {
  color.value = c;
  let t = performance.now()
  const dom = document.getElementById('box_' + (count.value - 1))
  let timer:any;
  timer = setInterval(() => {
    if (dom?.style.backgroundColor == c){
      time.value = Math.floor(performance.now() - t)
      timer && clearInterval(timer);
    }
  }, 50);
  return ;
}

const onMouseover = (e: MouseEvent) => {
  if (!e.target) return ;
  const dom = e.target as HTMLElement;
  // 随机取颜色
  const color = '#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0')
  dom.style.backgroundColor = color
}

const onMouseout = (e: MouseEvent) => {
  if (!e.target) return ;
  const dom = e.target as HTMLElement;
  dom.style.backgroundColor = color.value;
}


onMounted(() => {
  let t = performance.now()
  let timer:any;
  timer = setInterval(() => {
    if (document.getElementById('box_' + (count.value - 1))){
      time.value = Math.floor(performance.now() - t)
      timer && clearInterval(timer);
    }
  }, 50);
})

</script>
<style scoped>
.box {
  width: 20px;
  height: 20px;
  display: inline-block;
  background-color: aqua;
  text-align: center;
  margin-right: 5px;
  margin-bottom: 5px;
  cursor: pointer;
}
</style>
